package juc.utils.phaser;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

public class PhaserExample6 {
    private final static Random random = new Random(System.currentTimeMillis());

    /**
     * arrive()，到达后立即返回，不等待其他线程
     */
    public static void main(String[] args) throws InterruptedException {
        /*final Phaser phaser = new Phaser(3);
        //new Thread(phaser::arriveAndAwaitAdvance).start();
        new Thread(phaser::arrive).start();
        TimeUnit.SECONDS.sleep(5);*/

        final Phaser phaser=new Phaser(5);
        for (int i = 0; i < 4; i++) {
            new ArriveTask(phaser,i).start();
        }

        phaser.arriveAndAwaitAdvance();
        System.out.println("the phase 1 work finished done");
    }

    private static class ArriveTask extends Thread {
        private final Phaser phaser;

        private ArriveTask(Phaser phaser, int no) {
            super(String.valueOf(no));
            this.phaser = phaser;
        }

        @Override
        public void run() {
            System.out.println(getName() + " start working");
            timeSleep(2);
            System.out.println(getName() + " the phase one is running ");
            phaser.arrive();
            timeSleep(5);
            System.out.println(getName() + " keep to do other thing ");

        }
    }

    private static void timeSleep(long time) {
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
